package com.example.canaldemospringboot.canal;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Description:
 * @Author: dengPing.xu
 * @Data: 2022-01-14
 */
@Slf4j
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4);
        //异步任务组合
        CompletableFuture[] futures = list.stream().map(item -> CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(item * 1000);
                System.out.println(item + "  -------");
                return null;
            } catch (Exception e) {
                log.warn("查询零件号错误", e);
            }
            return null;
        }).whenComplete((ret, e) -> {
            if (e != null) {
                log.warn("查询零件号错误", e);
            } else if (ret != null) {
                System.out.println(ret);
            }
        })).toArray(CompletableFuture[]::new);
        try {
            //设置最多处理时间；
            long currentTime = System.currentTimeMillis();
            CompletableFuture.allOf(futures).get();
            log.info("并发查询时间耗费 -> {}", System.currentTimeMillis() - currentTime);
        } catch (InterruptedException e) {
            log.error("零件号查询线程中断", e);
        } catch (ExecutionException e) {
            log.error("零件号查询查询错误", e);
        }
    }
}
